var express = require('express');
var router = express.Router();
const { v4: uuidv4 } = require('uuid');
const Query = require('../tools/db')
const md5 = require('md5');
const { setToken, getToken } = require('../tools/token')
const { secret, image_url } = require('../config/config')

/* GET home page. */
//注册功能
router.post('/register', async function (req, res, next) {
  let { username, password, password2 } = req.body;
  //1.非空判断
  if (!username || !password || !password2) {
    next('账户或尼玛不能为空');
    return;
  }
  if (password !== password2) {
    next('两次密码不一致');
    return;
  }
  //2.查找用户名是否被占用
  let sql1 = `SELECT *FROM e_member WHERE username ='${username}'`
  let [err1, result1] = await Query(sql1);
  if (err1) {
    next('服务器内部错误');
    return;
  }
  if (result1.length) {
    next('用户名已占用');
    return;
  }
  // 3、向数据库插入一条数据
  // 不能为空的数据
  // id:不用管
  // mid:用户id  使用uuid模块生成   npm i uuid
  // username:通过ajax传递
  // password:肯定要加密
  // createdate:注册时间
  let passwordmd5 = md5(secret + password);
  let sql2 = `INSERT INTO e_member (mid,username,password,createdate) VALUES ('${uuidv4()}','${username}','${passwordmd5}','${Date.now()}')`
  let [err2, result2] = await Query(sql2);
  if (err2) {
    next('服务器内部错误');
    return;
  }
  if (result2.affectedRows) {
    res.send({
      code: 200,
      msg: '注册成功'
    })
  }
});
//登录功能
router.post('/login', async function (req, res, next) {
  //1.获取输入
  let { username, password } = req.body;
  //2.必要判断
  if (!username || !password) {
    next('用户或密码必须输入');
    return;
  }
  //3.查数据库
  let passwordmd5 = md5(secret + password);
  let sql = `SELECT *FROM e_member WHERE username ='${username}' AND password = '${passwordmd5}'`
  let [err, result] = await Query(sql);
  if (err) {
    next('服务器内部错误');
    return;
  }
  if (!result.length) {
    next('用户名和密码不匹配');
    return;
  }
  res.send({
    code: 200,
    msg: '登陆成功',
    result: {
      mid: result[0].mid,//用户ID
      username: result[0].username,//用户名
      head_photo_url: image_url + '/uploads/photo/' + result[0].head_photo_url,//用户头像
      token: setToken({
        mid: result[0].mid,
        username: result[0].username,
      })
    }
  })
});
module.exports = router;
